﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Xml.Serialization;
using bmapi.HelperClass;
using bmapi.Models.CADModel;
using bmapi.Models.DataEntity;

namespace bmapi.Controllers
{
    [RoutePrefix("cadFinish")]
    public class CADFinishController : CADController
    {

        [HttpPost,Route("GoBack")]
        public string GoBack([FromBody]dynamic json)
        {
            return ReturnError(200, "OK");
        }

        [HttpPost,Route("Stop")]
        public string Stop([FromBody]dynamic json)
        {
            return ReturnError(200, "OK");
        }


        // GET: api/Finish
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }
        /// <summary>
        /// 上传样板 只有工序编号是13或23的用户才可以调用
        /// </summary>
        /// <param name="obj">id款式id name样板名 go 进入下一道工序(1) upload上传了样板文件(2) file上传文件的文件名（或者文件夹名），在员工目录下</param>
        public bool UploadModelFile(dynamic obj)
        {
            int loginid = GetCrrentIDByToken();
            string modelName = obj.nmae.ToString();
            int styleId = Convert.ToInt32(obj.id);
            int go = Convert.ToInt32(obj.go);
            int upload = Convert.ToInt32(obj.upload);
            string file = obj.file.ToString();
            string sql = "";
            SQLCommand sc = new SQLCommand("select name from Model_tb where name=@name", "@name", modelName);
            string mname= sc.ExecuteScalar();
            if (mname != null)
                return false;
            else
            {
                sql = "select PLID from User_tb where login_id=@id";
                sc = new SQLCommand(sql, "@id", loginid);
                int plid = Convert.ToInt32(sc.ExecuteScalar());
                sql = "insert into Model_tb values(@id,@name,@loginid,@time,'',@styleid,@plid,0,2)";
                sc = new SQLCommand(sql);
                sc.Add("@id", GetNewSafeID(loginid));
                sc.Add("@name", modelName);
                sc.Add("@loginid", loginid);
                sc.Add("@time", DateTime.Now);
                sc.Add("@styleid", styleId);
                sc.Add("@plid", plid);
                if (sc.ExecuteNonQuery() == 1)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }

        [HttpPost,Route("CreateDir")]
        public string CreateDir(dynamic json)
        {
            WriteDebug("CADFinish/CreateDir", "1");
            string dirPath = GetPCPath(json.name.ToString());
            int code = Convert.ToInt32(json.process);
            if (!Directory.Exists(dirPath))
            {
                //目标目录不存在则创建  
                try
                {
                    Directory.CreateDirectory(dirPath);
                }
                catch (Exception ex)
                {
                    throw new Exception("创建目标目录失败：" + ex.Message);
                }
            }
            else
            {
                Directory.Delete(dirPath,true);
                Directory.CreateDirectory(dirPath);
            }
            return "true";
        }


        private void Move(string file,string userPath,string stylePath)
        {
            if (File.Exists(file)) //文件
            {
                File.Move(userPath + "\\" + file, stylePath + "\\" + file);
            }
            else if (Directory.Exists(file)) //文件夹
            {
                Directory.Move(userPath + "\\" + file, stylePath + "\\" + file);
            }
        }


        protected int ChangeProcessState(PC pc)
        {
            //download是bit数据类型
            pc.download = 0;
            WriteDebug("ChangeProcessState","pcmaxstep"+pc.maxStep);
            string sql = "update PC_tb set step=@step,download=@down,station=@station where pc_id=@pcid";
            SQLCommand sc = new SQLCommand(sql);
            sc.Add("@step", pc.step);
            sc.Add("@down", 0);
            sc.Add("@station", pc.station);
            sc.Add("@pcid", pc.pc_id);
            return  sc.ExecuteNonQuery();
        }

        /// <summary> 
        /// 在某一道工序完成时, 改变流程状态
        /// </summary>每个工序结束后被调用  
        /// <param name="pcid">流程的pcid</param>
        /// <param name="code">当前工序</param>
        /// <returns>返回1表示成功</returns> 
        protected int ChangeProcessState(int code, int pcid)
        { 
            int rtn = 0;
            string sql = "";
            SQLCommand sc = null;
            try
            {
                PC pc = GetPC(pcid);
                if (pc == null)
                    return 0;

                //获得下一道工序
                Process next = GetNextProcess(pc.PLID, code);
                pc.step = next.code;

                if (next.code == next.doerCode)
                {
                    //不是兼职  
                    if (pc.maxStep >= next.code) //37是  pcmax是34 
                    {
                        //下一道工序是返工状态
                        if(IsOracle)
                            sql = "select user_id from Task_tb where rownum<2 and id=@pcid and code=@code order by time desc";
                        else
                            sql = "select top 1 user_id from Task_tb where id=@pcid and code=@code order by time desc";

                        sc = new SQLCommand(sql);
                        sc.Add("@pcid", pc.pc_id);
                        sc.Add("@code", next.code);
                        pc.station = Convert.ToInt32(sc.ExecuteScalar());
                    }
                    else
                    {
                        //下一道工序是自由分配
                        pc.station = 0;
                    }
                }
                else
                {
                    //兼职工序
                    if(IsOracle)
                        sql = "select user_id from Task_tb where rownum<2 and id=@pcid and code=@code order by time desc";
                    else
                        sql = "select top 1 user_id from Task_tb where id=@pcid and code=@code order by time desc";
                    sc = new SQLCommand(sql);
                    sc.Add("@pcid", pc.pc_id);
                    sc.Add("@code", next.code);
                    pc.station = Convert.ToInt32(sc.ExecuteScalar());
                }
                rtn = ChangeProcessState(pc);
            }
            catch (Exception e)
            {
                WriteLog("ChangeProcessState", e.Message);
                rtn = 0;
            }
            return rtn;
        }



        /// <summary>
        /// 判断当前用户是否可以结束pcid指定的流程中的当前工序
        /// </summary>
        /// <returns> 0 表示可以结束本工序 </returns>
        protected int CanFinishTask(int loginid, int code, int pcid)
        {
            string sql = "select station from PC_tb where pc_id=@pcid and step=@code";
            SQLCommand sc = null;
            sc = new SQLCommand(sql);
            sc.Add("@pcid", pcid);
            sc.Add("@code", code);
            string station = sc.ExecuteScalar();

            WriteDebug("CanFinishTask","station:"+station);

            if (station == null)
                return 1;
            else
            {
                if (Convert.ToInt32(station) == loginid)
                    return 0;
                else
                {
                    sc = new SQLCommand("select power from User_tb where login_id=@station", "@station", station);
                    string power = sc.ExecuteScalar();
                    WriteDebug("CanFinishTask", "power:" + power);
                    if (Convert.ToInt32(power) == 1)
                        return 0;
                    else
                        return 2;
                }
            }
        }
    }
}
